package com.wrt.sps.shiro;

import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.filter.authc.LogoutFilter;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.Filter;

/**
 * shiro配置
 * 
 * @author 文瑞涛
 * @date 2021年1月7日 下午10:08:24
 */
@Configuration
public class ShiroConfig {

	private static final String LOGIN_URL = "/mgt/index";

	/**
	 * 
	 * Filter工厂，设置对应的过滤条件和跳转条件
	 * 
	 * @param 安全管理 securityManager
	 * 
	 * @return 过滤工厂
	 */
	@Bean
	public ShiroFilterFactoryBean shiroFilterFactoryBean(CustomRealm customRealm) {
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		securityManager.setRealm(customRealm);
		shiroFilterFactoryBean.setSecurityManager(securityManager);
		Map<String, String> map = new HashMap<>(5);
		// 登出
		map.put("/logout", "logout");
		// 免认证路径
		map.put(LOGIN_URL, "anon");
		map.put("/mgt/login", "anon");
		map.put("/html/**", "anon");
		// 认证
		map.put("/mgt/**", "authc");
		// 登录
		shiroFilterFactoryBean.setLoginUrl(LOGIN_URL);
		// 首页
		shiroFilterFactoryBean.setSuccessUrl("/mgt/main");
		// 错误页面，认证不通过跳转
		shiroFilterFactoryBean.setUnauthorizedUrl("/error");
		shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
		// 修改登出后跳转地址
		Map<String, Filter> filtersMap = new LinkedHashMap<>(1);
		// 修改logout后的地址
		LogoutFilter logout = new LogoutFilter();
		logout.setRedirectUrl(LOGIN_URL);
		filtersMap.put("logout", logout);
		shiroFilterFactoryBean.setFilters(filtersMap);
		return shiroFilterFactoryBean;
	}

	@Bean
	@ConditionalOnMissingBean
	public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(ShiroFilterFactoryBean shiroFilterFactoryBean) {
		AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
		authorizationAttributeSourceAdvisor.setSecurityManager(shiroFilterFactoryBean.getSecurityManager());
		return authorizationAttributeSourceAdvisor;
	}

}
